﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace OA.Common
{
    public class CaptchaHelper
    {
        /// <summary>
        ///  验证码 Key
        /// </summary>
        static string SessionName = "OA_Captcha";

        /// <summary>
        ///  生成图形验证码
        ///  并保存到 Session
        /// </summary>
        /// <returns></returns>
        public static byte[] GenerateCaptcha()
        {
            var _code = GenerateCode();
            HttpContext.Current.Session[SessionName] = _code;
            return GenerateGraphic(_code);
        }

        /// <summary>
        ///  检查验证码是否正确
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static bool Check(string code)
        {
            return HttpContext.Current.Session[SessionName]?.ToString() == code;
        }

        /// <summary>
        ///  清除验证码
        /// </summary>
        public static void ClearSession()
        {
            HttpContext.Current.Session[SessionName] = null;
        }

        



        /// <summary>
        ///  生成图形验证码代码
        /// </summary>
        /// <param name="length">代码长度</param>
        /// <returns></returns>
        private static string GenerateCode(int length = 4)
        {
            string[] s1 = {
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                /*"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"*/
            };

            var vcode = "";
            var rand = new Random();

            for (var i = 0; i < length; i++)
            {
                vcode += s1[rand.Next(0, s1.Length)];
            }

            return vcode;
        }
        
        /// <summary>
        ///  根据验证码代码生成验证码图片
        /// </summary>
        /// <param name="validateCode">验证码代码</param>
        /// <returns></returns>
        private static byte[] GenerateGraphic(string validateCode)
        {
            var image = new Bitmap((int)Math.Ceiling(validateCode.Length * 20.9), 32);
            var g = Graphics.FromImage(image);

            var fontList = new List<Font>();
            fontList.Add(new Font("微软雅黑", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("微软雅黑", 19, (FontStyle.Bold)));
            fontList.Add(new Font("微软雅黑", 19, (FontStyle.Regular)));
            fontList.Add(new Font("微软雅黑", 19, (FontStyle.Italic)));
            fontList.Add(new Font("宋体", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("宋体", 19, (FontStyle.Bold)));
            fontList.Add(new Font("宋体", 19, (FontStyle.Regular)));
            fontList.Add(new Font("宋体", 19, (FontStyle.Italic)));
            fontList.Add(new Font("黑体", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("黑体", 19, (FontStyle.Bold)));
            fontList.Add(new Font("黑体", 19, (FontStyle.Regular)));
            fontList.Add(new Font("黑体", 19, (FontStyle.Italic)));
            fontList.Add(new Font("Arial", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("Arial", 19, (FontStyle.Bold)));
            fontList.Add(new Font("Arial", 19, (FontStyle.Regular)));
            fontList.Add(new Font("Arial", 19, (FontStyle.Italic)));

            fontList.Add(new Font("Tahoma", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("Tahoma", 19, (FontStyle.Bold)));
            fontList.Add(new Font("Tahoma", 19, (FontStyle.Regular)));
            fontList.Add(new Font("Tahoma", 19, (FontStyle.Italic)));
            fontList.Add(new Font("华文中宋", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("华文中宋", 19, (FontStyle.Bold)));
            fontList.Add(new Font("华文细黑", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("华文细黑", 19, (FontStyle.Bold)));
            fontList.Add(new Font("华文细黑", 19, (FontStyle.Regular)));
            fontList.Add(new Font("华文细黑", 19, (FontStyle.Italic)));

            fontList.Add(new Font("Raavi", 19, (FontStyle.Bold | FontStyle.Italic)));
            fontList.Add(new Font("Raavi", 19, (FontStyle.Bold)));
            fontList.Add(new Font("Raavi", 19, (FontStyle.Regular)));
            fontList.Add(new Font("Raavi", 19, (FontStyle.Italic)));

            var backColorList = new List<Color>();
            backColorList.Add(Color.Yellow);
            backColorList.Add(Color.FromArgb(248, 209, 230));
            backColorList.Add(Color.FromArgb(221, 235, 225));
            backColorList.Add(Color.FromArgb(241, 253, 255));
            backColorList.Add(Color.FromArgb(252, 242, 198));
            backColorList.Add(Color.FromArgb(247, 238, 249));
            backColorList.Add(Color.FromArgb(200, 252, 219));
            backColorList.Add(Color.FromArgb(224, 219, 219));
            backColorList.Add(Color.FromArgb(237, 237, 189));
            backColorList.Add(Color.FromArgb(201, 241, 254));
            backColorList.Add(Color.FromArgb(130, 211, 13));


            var colorList = new List<Color>();
            colorList.Add(Color.Black);
            colorList.Add(Color.Red);
            colorList.Add(Color.Green);
            colorList.Add(Color.DarkGreen);
            colorList.Add(Color.Brown);
            colorList.Add(Color.FromArgb(138, 25, 158));
            colorList.Add(Color.FromArgb(56, 25, 123));
            colorList.Add(Color.FromArgb(156, 25, 22));
            colorList.Add(Color.FromArgb(47, 79, 145));
            colorList.Add(Color.FromArgb(96, 69, 104));
            colorList.Add(Color.FromArgb(110, 123, 26));


            try
            {
                var cr = new Random();
                //生成随机生成器
                var random = new Random();
                //清空图片背景色
                //g.Clear(backColorList.OrderBy(m => Guid.NewGuid()).FirstOrDefault());
                g.Clear(Color.FromArgb(cr.Next(150, 254), cr.Next(150, 254), cr.Next(150, 254)));
                //画图片的干扰线

                //var fontColor = colorList.OrderBy(m => Guid.NewGuid()).FirstOrDefault();
                //var fontColor2 = colorList.OrderBy(m => Guid.NewGuid()).FirstOrDefault();
                var fontColor = Color.FromArgb(cr.Next(0, 160), cr.Next(0, 160), cr.Next(0, 160));
                var fontColor2 = Color.FromArgb(cr.Next(0, 160), cr.Next(0, 160), cr.Next(0, 160));


                //随机数越大线条越多
                for (var i = 0; i < random.Next(1, 3); i++)
                {
                    var x1 = random.Next(image.Width);
                    var x2 = random.Next(image.Width);
                    var y1 = random.Next(image.Height);
                    var y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(colorList.OrderBy(m => Guid.NewGuid()).FirstOrDefault()), x1, y1, x2, y2);
                    //image.SetPixel(x1, y2, Color.Green);
                }

                var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 colorList.OrderBy(m => Guid.NewGuid()).FirstOrDefault(), colorList.OrderBy(m => Guid.NewGuid()).FirstOrDefault(), 1.1f, true);
                var jjrand = new Random();
                for (int i = 0; i < validateCode.Length; i++)
                {
                    var jjr = jjrand.Next(16, 20);
                    g.DrawString(validateCode[i].ToString(), fontList.OrderBy(m => Guid.NewGuid()).FirstOrDefault(), brush, jjr * i, 1);

                }

                //g.DrawString(validateCode, fontList.OrderBy(m => Guid.NewGuid()).FirstOrDefault(), brush, 1, 1);
                //画图片的前景干扰点
                for (var i = 0; i < 40; i++)
                {
                    var x = random.Next(image.Width);
                    var y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.Green);
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                var stream = new MemoryStream();

                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}
